package com.vf.cloud.pass.mvc.biz.service.impl;

import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.vf.cloud.pass.common.domain.biz.Terminal;
import com.vf.cloud.pass.common.util.R;
import com.vf.cloud.pass.common.vo.Renderer;
import com.vf.cloud.pass.common.vo.req.AnyInfoParam;
import com.vf.cloud.pass.mvc.biz.service.ITerminal;

@Service
public class TerminalImpl implements ITerminal{

	@Override
	public R<String> getRemoteInfo(String id) {
		Terminal terminal = Terminal.dao.findById(id);
		if(terminal==null) {
			return R.failed("数据不存在，刷新后尝试!");
		}
		
		
		String nodeUrl = String.format("http://%s:%s/Renderers/Any/info", terminal.getIp(), terminal.getPort());
		HttpClient httpClient = new HttpClient();

		PostMethod method = new PostMethod(nodeUrl);
		try {
			
			AnyInfoParam param=new AnyInfoParam();
			param.setId(id);
			
			RequestEntity requestEntity = new StringRequestEntity(JsonKit.toJson(param), "application/json", "UTF-8");
			method.setRequestEntity(requestEntity);
			int code = httpClient.executeMethod(method);
			if (code == 200) {
				JSONObject result = JSONObject.parseObject(new String(method.getResponseBody(), "UTF-8"));
				if (result.containsKey("code") && result.getInteger("code") == 200) {
					Renderer renderer=JSONObject.parseObject(result.getString("result"),Renderer.class);
					if(renderer==null) {
						return R.failed();
					}
					
//					1GiB=1024MiB，1MiB=1024KiB，1KiB=1024B；
//
//							1GiB/s=1024MiB/s，1MiB/s=1024KiB/s，1KiB/s=1024B/s。
//
//							1GB=1000MB，1MB=1000KB，1KB=1000B；
//
//							1GB/s=1000MB，1MB/s=1000KB，1KB/s=1000B。
//
//							1Gb/s=1000Mb/s，1Mb/s=1000Kb/s，1Kb/s=1000b/s。
					int gpuNum=0;
//					for(Gpu g:renderer.getGpus()) {
//						gpuNum+=1;
//					}
					terminal.setGpuNum(gpuNum);
					if(terminal.update()) {
						return R.ok();
					}
					return R.failed();
				} else if (result.containsKey("code") && result.getInteger("code") == 500) {
					return R.failed(result.getString("message"));
				} else {
					return R.failed(result.getString("message"));
				}
			} else {
				return R.failed(String.format("网络异常:【%s】.", code));
			}
		} catch (IOException e) {
			return R.failed(e.getMessage());
		}
		
	}

}
